import json
import logging
import re
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import datetime
import requests
import random
novelurl="https://www.xbiquge.la/24/24770//"       #小说重生唐三的笔趣阁网址
header = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.30"
}

def getlink(link,time):
    response = requests.get(novelurl, headers=header)
    #print(response.content.decode("utf-8"))
    #print(type(response.content.decode("utf-8")))       #为str类型
    all_novel = response.content.decode("utf-8")
    latest_novel_rule=re.compile(r'<div id="maininfo">(.*?)<div id="intro">', re.S)
    latest_novels = re.findall(latest_novel_rule, all_novel)
    #print(latest_novels)#爬取最新章节有关信息
    latest_novels = str(latest_novels)
    time_rule=re.compile(r' <p>最后更新：(.*?)</p>')
    latest_time=re.search(time_rule, latest_novels).group()[9:-7]#匹配最新更新时间
    #print(latest_time)#打印最新更新时间
    latest_link=re.search(r'<p>最新章节：<a href="(.*?)>', latest_novels).group()[17:-2]#匹配最新更新章节链接
    #print(latest_link)#打印最新更新章节链接
    link=latest_link
    time=latest_time
    return link, time


def get_novel_content(latest_link):
    response1=requests.get(latest_link,headers=header)
    html_content=response1.content.decode("utf-8")
    #print(html_content)
    novel_content_rule=re.compile(r'&nbsp;&nbsp;&nbsp;&nbsp;(?P<content>.*?)<br />',re.S)
    it=re.finditer(novel_content_rule,html_content)
    for x in it:
        #print(x.group("content"))
        a = x.group("content").replace("&nbsp;", "\n")#字符串替换，将&nbsp;替换为换行
        f.write(a)


def send_mail():
    try:
        msg_from = '382152588@qq.com'  # 发送方邮箱
        passwd = 'bsifdtwurahobhja'  # 填入发送方邮箱的授权码
        msg_to = '2351076618@qq.com'  # 收件人邮箱0

        subject = "你的小说更新了！！！"  # 主题
        content = "附件内是小说更新的最新章节"
        content = f.read()
        #print(content)
        msg = MIMEText(content)

        msg['Subject'] = subject
        msg['From'] = msg_from
        msg['To'] = msg_to

        try:
            s = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 邮件服务器及端口号
            s.login(msg_from, passwd)
            s.sendmail(msg_from, msg_to, msg.as_string())
            print("Send mail succed!")
        except s.SMTPException:
            print("Send mail failed")
        finally:
            s.quit()
    except Exception as result:
        print("发生异常！", result)


if __name__=="__main__":
    try:
        latest_time = ""
        latest_link = ""
        #print(type(getlink(latest_link,latest_time)[0]))
        # print(now_time)
        latest_time = getlink(latest_link, latest_time)[1]
        print(latest_time)
        #new_time = latest_time
        new_time=""
        #new_time ="2022-03-06 17:02"
        while True:
            t = random.randint(0, 30)#增加随机数睡眠，防止爬取过于暴力，爬崩网站，或ip被封
            time.sleep(t)
            latest_time = getlink(latest_link, latest_time)[1]#获取当前小说最后一次更新的时间
            if latest_time!=new_time:#如果与上一次时间不同
                print("小说已更新！")
                print("更新时间:", new_time)  # 打印小说更新时间
                f = open("最新章节.txt", "w", encoding="utf-8")
                time.sleep(60)
                get_novel_content(getlink(latest_link,latest_time)[0])#将更新章节写入最新章节.txt
                f.close()
                print("小说已写入文本文件！！！")
                f = open("最新章节.txt", "r", encoding="utf-8")
                send_mail()
                f.close()
                new_time = latest_time#更新小说最后一次更新的时间

            else:
                pass


        #get_novel_content(getlink(latest_link,latest_time)[0])
    except Exception as result:
        print("发生异常！！！",result)
